var urlArr = {
    "bing": {
        "name": "必应",
        "url": "https://cn.bing.com/search?q="
    },
    "baidu": {
        "name": "百度",
        "url": "https://www.baidu.com/s?wd="
    },
    "google": {
        "name": "谷歌",
        "url": "https://www.google.com/search?q="
    },
    "github": {
        "name": "GH",
        "url": "https://github.com/search?q="
    },
    "bili": {
        "name": "B站",
        "url": "https://search.bilibili.com/all?keyword="
    },
    "weibo": {
        "name": "微博",
        "url": "https://s.weibo.com/weibo/"
    },
    "gitee": {
        "name": "码云",
        "url": "https://search.gitee.com/?q="
    }
};

var selectedLiKey = 0;

$(function () {
    initPage();
    $('.search-tab ul').on('click', 'li', function () {
        var itemName = $(this).attr('data');
        console.log(itemName);
        changeSearchItem(itemName)
    });
    $('.search-form button').on('click', function () {
        goSearch();
    });

    $(document).keydown(function (event) {
        if (
            event.keyCode != 13
            && event.keyCode != 27
            && event.keyCode != 38
            && (event.keyCode < 49 || event.keyCode > 57)
        ) {
            if (!$('.search-form input').is(":focus")) {
                $('.search-form input').focus();
            }
            if (event.keyCode == 32){
                return  false
            }
        }
    });

    $(document).keyup(function (event) {
        if (event.keyCode == 13) { //enter
            goSearch();
        } else if (event.keyCode == 27) {  //esc
            $('.search-form input').blur();
        } else if (event.keyCode >= 49 && event.keyCode <= 57) {  //1 ～ 6
            if (!$('.search-form input').is(":focus")) {
                var i = event.keyCode - 48;
                $('.search-tab ul').children('li:nth-child(' + i + ')').click();
            }
        } else if (event.keyCode == 38) {  //  up
            return false;
        }
    });
    $(document).keydown(function (event) {
        if (event.keyCode == 38 || event.keyCode == 40) {
            var keyCode = event.keyCode
            if (keyCode == 38) {
                selectedLiKey -= 1;
            } else if (keyCode == 40) {
                selectedLiKey += 1;
            }

            var maxKey = $('.sug').children('li').length;
            if (selectedLiKey <= 0) {
                selectedLiKey = maxKey;
            }
            if (selectedLiKey > maxKey) {
                selectedLiKey = 1;
            }
            $('.sug li').css('background-color', '#ffffff');
            $('.sug').children('li:nth-child(' + selectedLiKey + ')').css('background-color', '#e5e5e5');
            var word = $('.sug').children('li:nth-child(' + selectedLiKey + ')').text();
            if (word != '' && word != undefined) {
                $('.search-form input').focus().val(word)
            }
            if (keyCode == 38) {
                return false;
            }
        }
    });
    $('.search-form input').on('focus', function (e) {
        $('.search-div').css('opacity', 1);
        if ($(window).width() <= 960) {
            $('.page-background').css('padding-top', '10vh');
            $('.page-background').css('height', '90vh');
        }
    });
    $('.search-form input').on('blur', function (e) {
        $('.search-div').css('opacity', '');
        // if ($(window).width() <= 960 && $('.search-form input').val().length == 0) {
        //     $('.page-background').css('padding-top', '55vh');
        //     $('.page-background').css('height', '45vh');
        // }
    });
    $('.re-bg').on('click', function () {
        $('.re-bg').css('animation', 'turn 1s linear 1');
        $('.re-bg').css('pointer-events', 'none');
        $('.re-bg').css('cursor', 'wait');
        changeBg();
    });
    $('.search-form input').on('input propertychange', function () {
        selectedLiKey = 0;
        $('.sug').html('');
        var wordKey = $('.search-form input').val();
        var url = 'https://www.baidu.com/sugrec?json=1&prod=pc&wd=' + encodeURI(wordKey) + '&cb=jQ';
        $.ajax({
            url: url,
            type: 'get',
            dataType: 'jsonp',  // 请求方式为jsonp
            crossDomain: true,
            success: function (data) {
            },
            data: {}
        });

        if ($(window).width() <= 960) {
            if (wordKey.length > 0) {
                $('.page-background').css('padding-top', '10vh');
                $('.page-background').css('height', '90vh');
            } else {
                $('.page-background').css('padding-top', '55vh');
                $('.page-background').css('height', '45vh');
            }

        }

    });

    $('.sug').on('click', 'li', function () {
        $('.search-form input').val($(this).text())
        $('.sug').html('');
        $('.sug').css('display', 'none');
        $('.search-form input').focus();
    });

    $('.sug').on('mouseover', 'li', function () {
        $('.sug li').css('background-color', '#ffffff');
        $(this).css('background-color', '#e5e5e5');
    });

});

function jQ(data) {
    var word = '';
    var sugHtml = '';
    for (key in data.g) {
        if (data['g'][key]['type'] == 'sug') {
            word = data['g'][key]['q'];
            if (word != '' && word != undefined) {
                sugHtml += '<li>' + word + '</li>';
            }
        }
    }
    $('.sug').html(sugHtml);
    if (sugHtml != '') {
        $('.sug').css('display', 'block');
    } else {
        $('.sug').css('display', 'none');
    }

}

function initPage() {
    var searchUrlItem = localStorage['searchUrlItem'];
    if (searchUrlItem == undefined) {
        localStorage['searchUrlItem'] = "bing";
    }
    refreshTab();
    refreshBg();
}

function refreshTab() {
    var liHtml = "";
    for (v in urlArr) {
        if (v == localStorage['searchUrlItem']) {
            liHtml += "<li data='" + v + "' class='active'>" + urlArr[v]['name'] + "</li>";
        } else {
            liHtml += "<li data='" + v + "'>" + urlArr[v]['name'] + "</li>";
        }
    }
    $('.search-tab ul').html(liHtml)
}

function changeSearchItem(itemName) {
    $('.search-form input').focus();
    localStorage['searchUrlItem'] = itemName;
    refreshTab();
}

function goSearch() {
    var w = $('.search-form input').val();
    console.log(w)
    if (w == '') {
        return;
    }
    var url = urlArr[localStorage['searchUrlItem']]['url'];
    url += w;
    $(location).attr('href', url);
}


function changeBg() {
    // var bingUrl = 'https://bing.ioliu.cn/v1/rand?type=json';
    // // var bingUrl = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1';
    // $.ajax({
    //     url: bingUrl,
    //     type: 'get',
    //     dataType: 'jsonp',  // 请求方式为jsonp
    //     crossDomain: true,
    //     success: function (data) {
    //         var imgUrl = data.data.url
    //         imgUrl = imgUrl.replace('http://h1.ioliu.cn/','https://h2.ioliu.cn/')
    //         localStorage['imgUrl'] = imgUrl
    //         localStorage['imgDate'] = getYd();
    //         refreshBg();
    //     },
    //     data: {}
    // });
    localStorage['imgUrl'] = ''
    refreshBgV2()
    setInterval(function () {
        $('.re-bg').css('pointer-events', '');
        $('.re-bg').css('cursor', '');
        $('.re-bg').css('animation', '');
    }, 3000)
}

function getYd() {
    var myDate = new Date();
    var Y = myDate.getFullYear();
    var m = myDate.getMonth() + 1;
    if (m < 10) {
        m = '0' + m;
    }
    var d = myDate.getDate();
    if (d < 10) {
        d = '0' + d;
    }
    return Y + m + d;
}

function refreshBg() {
    refreshBgV2()
    return
    var theDate = getYd();
    var imgUrl = localStorage['imgUrl'];
    if (imgUrl == undefined || localStorage['imgDate'] != theDate) {
        bingUrl = 'https://bing.ioliu.cn/v1?type=json';

        $.ajax({
            url: bingUrl,
            type: 'get',
            dataType: 'jsonp',  // 请求方式为jsonp
            crossDomain: true,
            success: function (data) {
                imgUrl = data.data.url
                localStorage['imgUrl'] = imgUrl
                localStorage['imgDate'] = getYd();
                $('.page-background').css('background-image', 'url(' + imgUrl + ')');
            },
            data: {}
        });
    }
    $('.page-background').css('background-image', 'url(' + imgUrl + ')');
}


function refreshBgV2() {
    var theDate = getYd();
    var imgUrl = localStorage['imgUrl'];
    if (imgUrl == undefined || imgUrl == '' || localStorage['imgDate'] != theDate) {
        console.log('refreshBgV2')
        link = 'https://unsplash.it/1600/900?random';
        var xhr = new XMLHttpRequest();
        xhr.open('GET', link, true);
        xhr.onload = function () {
            imgUrl = xhr.responseURL
            console.log(imgUrl)
            localStorage['imgUrl'] = imgUrl
            localStorage['imgDate'] = getYd();
            $('.page-background').css('background-image', 'url(' + imgUrl + ')');
        }
        xhr.send(null);
    }
    $('.page-background').css('background-image', 'url(' + imgUrl + ')');
}

